package cn.stylefeng.guns.modular.tool.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.AreaId;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.tool.entity.ToolTaskArrange;
import cn.stylefeng.guns.modular.tool.entity.ToolWave;
import cn.stylefeng.guns.modular.tool.mapper.ToolTaskArrangeMapper;
import cn.stylefeng.guns.modular.tool.model.params.ToolTaskArrangeParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolTaskArrangeResult;
import  cn.stylefeng.guns.modular.tool.service.ToolTaskArrangeService;
import cn.stylefeng.guns.modular.tool.service.ToolWaveService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 工作安排 服务实现类
 */
@Service
public class ToolTaskArrangeServiceImpl extends ServiceImpl<ToolTaskArrangeMapper, ToolTaskArrange> implements ToolTaskArrangeService {

    @Override
    public void add(ToolTaskArrangeParam param){
        ToolTaskArrange entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ToolTaskArrangeParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ToolTaskArrangeParam param){
        ToolTaskArrange oldEntity = getOldEntity(param);
        ToolTaskArrange newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ToolTaskArrangeResult findBySpec(ToolTaskArrangeParam param){
        return this.baseMapper.findBySpec(param);
    }

    @Override
    public List<ToolTaskArrangeResult> findListBySpec(ToolTaskArrangeParam param){
        return this.baseMapper.findListBySpec(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(ToolTaskArrangeParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(ToolTaskArrangeParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ToolTaskArrange getOldEntity(ToolTaskArrangeParam param) {
        return this.getById(getKey(param));
    }

    private ToolTaskArrange getEntity(ToolTaskArrangeParam param) {
        ToolTaskArrange entity = new ToolTaskArrange();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	@Override
	public void deleteBySpec(ToolTaskArrangeParam toolTaskArrangeParam) {
		this.baseMapper.deleteBySpec(toolTaskArrangeParam);
	}

	@Override
	public boolean saveBatchList(List<ToolTaskArrangeParam> list) {
		return this.baseMapper.saveBatchList(list);
	}
	
	@Resource
    private UserService userService;

	@Resource
    private ToolWaveService toolWaveService;

	@Resource
    private BasicPositionService basicPositionService;

	@Override
	@Transactional(rollbackFor = Exception.class,timeout = 600)
	public ResponseData getExceldata8(MultipartFile file,Long waveId, ResponseData data) throws IOException{
		User user = userService.getcurrentUser();
    	ToolWave toolWave = toolWaveService.getById(waveId);
		String fileName = file.getOriginalFilename();
    	List<ToolTaskArrangeParam> savelist = new ArrayList<ToolTaskArrangeParam>();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        
        BasicPositionParam positionParam = new BasicPositionParam();
        positionParam.setPositionAreaId(AreaId.arrangeAreaId);
        List<BasicPositionResult> list = basicPositionService.findListBySpec(positionParam, null, null, null, null);
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            ToolTaskArrangeParam param = new ToolTaskArrangeParam();
            param.setWaveId(waveId);
            param.setTaskDate(toolWave.getWaveName());
            
            String  groupNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(0));//小组编号
            if (ToolUtil.isNotEmpty(groupNumber)) {
//            	boolean duiying = false;
//            	for (BasicPositionResult pr : list) {
//					if(pr.getPositionNumber().equals(groupNumber)) {
//						duiying = true;
//						break;
//					}
//				}
//            	if (!duiying) {
//            		return ResponseData.error(groupNumber+"无对应的拣货位");
//				}
    			param.setGroupNumber(groupNumber);
			} else {
				continue;
			}
            
            String  groupUsers = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));//小组人员
            if (ToolUtil.isNotEmpty(groupUsers)) {
            	param.setGroupUsers(groupUsers);
			} else {
				continue;
			}
            
	    	ToolTaskArrangeParam check = new ToolTaskArrangeParam();
	    	check.setWaveId(waveId);
	    	check.setGroupNumber(groupNumber);
	    	check.setGroupUsers(groupUsers);
	    	ToolTaskArrangeResult checkResult = this.findBySpec(check);
	    	if(checkResult != null) {
				continue;
	    	}
	    	
            param.setDeptId(user.getDeptId());
            param.setCreateUserName(user.getName());
            param.setCreateTime(new Date());
            savelist.add(param);
        }
    	if(savelist.size()>0) {
    		this.saveBatchList(savelist);
    	}
		return ResponseData.success();
	}

	@Override
	public Integer addReturnId(ToolTaskArrangeParam taskArrangeParam) {
		return this.baseMapper.addReturnId(taskArrangeParam);
	}

}
